package com.wjy.sfhcore.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.MenuItem;
import android.view.View;

import com.wjy.sfhcore.CoreApplication;
import com.wjy.sfhcore.R;
import com.wjy.sfhcore.itf.OnNetStateChanged;
import com.wjy.sfhcore.util.ToastUtil;
import com.wjy.sfhcore.util.Tools;

import rx.android.view.ViewObservable;

/**
 * Created by wangjingyuan on 15/7/31.
 */
public abstract class LoadFragment<L> extends CoreFragment implements LoaderManager.LoaderCallbacks<L>, OnNetStateChanged {
    protected boolean isFirstLoad = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CoreApplication.getInstance().registerNetStateWatcher(this);
    }

    @Override
    public void onDestroy() {
        CoreApplication.getInstance().unRegisterNetStateWatcher(this);
        super.onDestroy();
    }

    @Override
    public void menuListener(MenuItem item) {

    }

    @Override
    public void initBackButton() {
        baseActivity.finish();
    }

    @Override
    public boolean isUseToolBar() {
        return true;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewObservable.clicks(viewLoadFail).subscribe(
                onClickEvent -> {
                    loadData();
                }
        );
        ViewObservable.clicks(viewNoNet).subscribe(
                onClickEvent -> {
                    if (!Tools.isConnectNet(baseActivity)) {
                        ToastUtil.toast(R.string.img_no_net);
                        return;
                    }
                    loadData();
                }
        );
    }


    @Override
    public void onNetStateChanged(boolean isNetConnect) {
        if (isNetConnect && viewNoNet.getVisibility() == View.VISIBLE) {
            loadData();
        }
    }

    /**
     * 发起数据加载
     */
    public void loadData() {
        if (Tools.isConnectNet(baseActivity)) {
            changeViewState(LoadResult.LOADING);
            getLoaderManager().restartLoader(0, null, this);
        } else {
            changeViewState(LoadResult.NO_NET);
        }
    }

    /**
     * 加载完成
     *
     * @param action 标示
     * @param result 数据
     */
    protected abstract void loadFinished(int action, L result);

    public abstract Loader<L> onCreateLoader(int action, Bundle bundle);

    public void onLoadFinished(Loader<L> arg0, L arg1) {
        int action = arg0.getId();
        getLoaderManager().destroyLoader(action);
        loadFinished(action, arg1);
    }

    public void onLoaderReset(Loader<L> arg0) {

    }


}
